package com.spit.fammo.ui.frg

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DensityUtil
import com.lxj.xpopup.XPopup
import com.spit.amoeba.base.BaseFragment
import com.spit.fammo.R
import com.spit.fammo.adapter.GridImageAdapter
import com.spit.fammo.bean.db.AssetBean
import com.spit.fammo.databinding.FAssetUploadBinding
import com.spit.fammo.ext.ASSET_NOT_PAGE
import com.spit.fammo.ext.ASSET_STOCK_PAGE
import com.spit.fammo.ext.SCAN_STATUS_MANUALLY
import com.spit.fammo.ext.STATUSID_ASSET_10
import com.spit.fammo.ext.STATUSID_ASSET_2
import com.spit.fammo.ext.UPLOAD_IMAGE_SPLIT
import com.spit.fammo.ext.showMessage
import com.spit.fammo.mar.eventViewModel
import com.spit.fammo.viewmodel.AssetModel
import com.spit.fammo.weight.FullyGridLayoutManager
import com.spit.fammo.weight.GlideEngine
import com.spit.fammo.weight.ImageFileCompressEngine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * User: Nike
 *  2025/1/8 17:18
 *      资产更新
 */
class AssetUploadFrg: BaseFragment<AssetModel, FAssetUploadBinding>() {

    var asstBean: AssetBean? = null

    val assetModel: AssetModel by activityViewModels()

    val imageAdapter by lazy { activity?.let { GridImageAdapter(it, localMediaList,) } }

    var localMediaList = ArrayList<LocalMedia?>()

    var default_state: Int = -1

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        arguments?.let {
            asstBean = Gson().fromJson(it.getString("bean"), AssetBean::class.java)
            mViewModel.remarks.set(asstBean?.remarks)
            mViewModel.assetStatus.set(asstBean?.type)
            mDatabind.tvStatus.setTextColor(if (asstBean?.type == ASSET_STOCK_PAGE) ContextCompat.getColor(requireContext(), R.color.colorPrimaryDark) else ContextCompat.getColor(requireContext(), R.color.red_ff0000))
            default_state = asstBean?.type!!

            val iamgeList = asstBean!!.imageList
            if (!StringUtils.isEmpty(iamgeList)){
                val split = iamgeList!!.split(UPLOAD_IMAGE_SPLIT)
                split.forEachIndexed(){index, path ->
                    if (!StringUtils.isEmpty(path)){
                        localMediaList.add(LocalMedia.generateLocalMedia(activity, path))
                    }
                }
            }
            val manager = FullyGridLayoutManager(activity,3, GridLayoutManager.VERTICAL, false)
            mDatabind.recyclerView.setLayoutManager(manager)
            val itemAnimator: RecyclerView.ItemAnimator? = mDatabind.recyclerView.getItemAnimator()
            if (itemAnimator != null) {
                (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            }
            mDatabind.recyclerView.addItemDecoration(
                GridSpacingItemDecoration( 3, DensityUtil.dip2px(activity, 8f), false)
            )
            mDatabind.recyclerView.adapter = imageAdapter
            imageAdapter!!.selectMax = 3
            imageAdapter!!.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
                override fun onItemClick(v: View?, position: Int) {
                    PictureSelector.create(activity)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                            override fun onPreviewDelete(position: Int) {
                                imageAdapter!!.delete(position)
                            }
                            override fun onLongPressDownload(context: Context?, media: LocalMedia?): Boolean {
                                return false
                            }
                        })
                        .startActivityPreview(position, true, imageAdapter!!.data)
                }

                override fun openPicture() {
                    PictureSelector.create(activity)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(3)
                        .setCompressEngine(ImageFileCompressEngine())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectedData(imageAdapter!!.data)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>) {
                                localMediaList.clear()
                                localMediaList.addAll(result)
                                imageAdapter!!.getData().clear()
                                imageAdapter!!.getData().addAll(result)
                                imageAdapter!!.notifyDataSetChanged()
                            }
                            override fun onCancel() {}
                        })
                }

            })
        }
    }

    inner class ProxyClick(){

        fun onConfirm(){
            if (asstBean == null)return
            val sb = StringBuffer()
            if (imageAdapter!!.data.size != 0){
                imageAdapter!!.data.forEachIndexed(){i, bean ->
                    if (bean!!.compressPath == null){
                        sb.append(bean!!.path).append(UPLOAD_IMAGE_SPLIT)
                    }else{
                        sb.append(bean!!.compressPath).append(UPLOAD_IMAGE_SPLIT)
                    }
                }
            }
            //存图片
            if (sb != null){
                asstBean!!.imageList = sb.toString()
            }
            //存出入库状态
            asstBean?.type = mViewModel.assetStatus.get()
            asstBean?.statusid = if (mViewModel.assetStatus.get() == ASSET_STOCK_PAGE) STATUSID_ASSET_2 else STATUSID_ASSET_10
            if (default_state != ASSET_STOCK_PAGE && asstBean?.type == ASSET_STOCK_PAGE){
                asstBean?.lastStockDate = TimeUtils.getNowString()
                asstBean?.scanTime = TimeUtils.getNowString()
                asstBean?.scanStatus = SCAN_STATUS_MANUALLY
            }
            //备注
            asstBean?.remarks = mViewModel.remarks.get()
            mViewModel.viewModelScope.launch {
                mViewModel.assetDao.update(asstBean!!)
                eventViewModel.uploadAsset.postValue(asstBean)
                withContext(Dispatchers.Main) {
                    showMessage(message = getString(R.string.success))
                }
            }
        }

        fun onStatus(){
            if (default_state == ASSET_STOCK_PAGE)return
            XPopup.Builder(context)
                .asCenterList(
                    getText(R.string.status), arrayOf(getString(R.string.in_library), getString(R.string.missing)),
                    null
                ) { position, text ->
                    mViewModel.assetStatus.set(if (position == 0) ASSET_STOCK_PAGE else ASSET_NOT_PAGE)
                    mDatabind.tvStatus.setTextColor(if (position == 0) ContextCompat.getColor(requireContext(), R.color.colorPrimaryDark) else ContextCompat.getColor(requireContext(), R.color.red_ff0000))
                }.show()
        }
    }
}